package com.book.util;

/**
 * @Author: 125715
 * @Package: com.book.util
 * @Date: 2025/4/3 0:48
 * @Description: 七牛云工具类
 */
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class QiniuUtil {

    @Value("${qiniu.access-key}")
    private String accessKey;

    @Value("${qiniu.secret-key}")
    private String secretKey;

    @Value("${qiniu.bucket-name}")
    private String bucketName;

    @Value("${qiniu.domain}")
    private String domain;

    /**
     * 上传文件到七牛云
     *
     * @param file 上传的文件
     * @return 文件的访问 URL
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + ".jpg";

        // 配置七牛云存储区域
        Configuration cfg = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(cfg);

        // 生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String uploadToken = auth.uploadToken(bucketName);

        // 上传文件
        try {
            Response response = uploadManager.put(file.getBytes(), fileName, uploadToken);
            if (response.isOK()) {
                // 返回文件的访问 URL
                return "http://" + domain + "/" + fileName;
            }
        } catch (QiniuException e) {
            e.printStackTrace();
        }
        return null;
    }
}

